package com.iflyteck.handler;

import com.iflyteck.config.ServerConfigUtil;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ZookeeperHandler {

    @Autowired
    private ServerConfigUtil serverConfigUtil;

    public void registerToZookeeper(Integer port) throws Exception {
        String zkServerConnectUrl = serverConfigUtil.getZkServerConnectUrl();
        System.out.println("zookeeper服务连接地址：" + zkServerConnectUrl);
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(zkServerConnectUrl,
                1000, 10000, retryPolicy);
        client.start(); // 启动会话

        // 拿到zookeeper服务器中创建根节点的
        String serverBaseNode = serverConfigUtil.getServerBaseNode();
        // 每个节点中存储的内容： ip+端口
        String serverData = "localhost:" + port;
        // 先判断有没有根节点
        Stat stat = client.checkExists().forPath(serverBaseNode);
        if (stat == null) {
            String providerRootPath = client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(serverBaseNode);
            System.out.println("注册服务根节点到zookeeper上，节点路径：" + providerRootPath);
        }
        // 每个服务对应的节点为临时节点，这样服务关闭后临时节点会被删除，从而客户端能够通过节点变更检测到服务端下线
        String providerServerPath = client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL) // 临时顺序节点
                .forPath(serverBaseNode + "/provider", serverData.getBytes());
        System.out.println("注册服务器临时节点到zookeeper上，节点路径是：" + providerServerPath);
    }
}
